<template>
  <el-dialog
    title="平台竞品"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    class="mt-dialog"
    top="15"
    width="80%"
    @close="close"
  >
    <div class="top">
      <el-input v-model="kwInput" placeholder="输入任意字符 进行筛选" clearable class="input-with-select">
        <el-select slot="prepend" v-model="platform" placeholder="platform" filterable size="mini" clearable style="width: 150px">
          <el-option
            v-for="item in platforms"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button slot="append" type="primary" icon="el-icon-search" :loading="listLoading" @click="handleSearch">搜索</el-button>
      </el-input>
      <el-button
        v-if="data.length!==0"
        type="danger"
        class="el-icon-remove"
        :disabled="listLoading"
        @click="handleDelete"
      >删除
      </el-button>
      <el-button
        v-else
        type="success"
        class="el-icon-plus"
        :disabled="listLoading"
        @click="handleAction('create', '添加竞品分析')"
      >添加分析
      </el-button>
    </div>
    <el-row v-if="translate_title !== ''">
      <span style="margin-left: 185px;">{{ translate_title }}</span>
    </el-row>
    <el-row>
      <el-card
        v-for="item in data"
        :key="item.id"
        class="box-card"
        shadow="hover"
        style="float: left; margin-right: 10px;margin-bottom: 10px;width: 200px;height: 300px; display: block"
      >
        <a :href="item.url" target="_blank"><img :src="item.image" class="image" style="width: 90px; height: 90px"></a>
        <div style="padding: 14px;">
          <span><small>{{ item.title }}</small></span>
          <div class="bottom clearfix">
            <div v-if="item.is_seed" style="position: fixed;">
              <span style="color: purple;display: block"><b>目标对比产品</b></span>
              <div v-if="item.price_list.length > 0">
                <span style="display: block">orders:{{ item.orders }}</span>
                <span v-if="item.volume || item.cpc" style="display: block"> CPC:{{ item.cpc }} volume:{{ item.volume }}</span>
                <span style="display: block">成本:<span style="color: red">{{ item.price }}</span></span>
                <span>均价:<span style="color: red">{{ item.average_price }}</span></span><span>总数:{{ item.products_count }}</span>
                <span style="display: block">up 2x:{{ item.price_list.filter(m => m >= item.price*2).length }}个 low:{{ item.price_list.filter(m => m <= item.price).length }}个</span>
                <span style="display: block" />
              </div>
              <el-button size="mini" type="success" plain @click="handleSetCrawlCount(item, 200)">可用</el-button>
              <el-button size="mini" type="danger" plain @click="handleSetCrawlCount(item, 300)">垃圾</el-button>
              <el-button size="mini" style="display: block" type="primary" plain @click="handleGetNext(item)">下一个</el-button>
            </div>
            <div v-else> <span style="color: red;display: block">{{ item.price }}</span>
              <el-link :href="item.url" target="_blank">{{ item.brand }}</el-link></div>

          </div>
        </div>
      </el-card>

      <el-card
        v-for="item in data[0].products"
        v-if="data.length > 0"
        :key="item.id"
        class="box-card"
        shadow="hover"
        style="float: left; margin-right: 10px;margin-bottom: 10px;width: 200px;height: 280px; display: block"
      >
        <a :href="item.url" target="_blank"><img :src="item.image" class="image" style="width: 90px; height: 90px"></a>
        <div style="padding: 14px;">
          <span><small>{{ item.title }}</small></span>
          <div class="bottom clearfix">
            <div v-if="item.is_seed">
              <span style="color: purple;display: block"><b>目标对比产品</b></span>
              <div v-if="item.price_list.length > 0">
                <span style="display: block">成本:<span style="color: red">{{ item.price }}</span></span>
                <span>均价:<span style="color: red">{{ item.average_price }}</span></span><span>总数:{{ item.products_count }}</span>
                <span style="display: block">高于2x:{{ item.price_list.filter(m => m >= item.price*2).length }}个</span>
                <span style="display: block">低于采购:{{ item.price_list.filter(m => m <= item.price).length }}个</span>
              </div>
              <el-button size="mini" type="success" plain @click="handleSetCrawlCount(item, 200)">可用</el-button>
              <el-button size="mini" type="danger" plain @click="handleSetCrawlCount(item, 300)">垃圾</el-button>
              <el-button size="mini" style="display: block" type="primary" plain @click="handleGetNext(item)">下一个产品</el-button>
            </div>
            <div v-else> <span style="color: red;display: block">{{ item.price }}</span>
              <el-link :href="item.url" target="_blank">{{ item.brand }}</el-link></div>

          </div>
        </div>
      </el-card>
    </el-row>
    <el-pagination
      v-if="data.length"
      background
      class="mt-pagination"
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />
    <el-dialog
      append-to-body
      :title="title"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="80px">

        <el-form-item label="keyword">
          <el-input v-model="temp.keyword" />
        </el-form-item>
        <el-form-item label="image">
          <el-input v-model="temp.image" />
        </el-form-item>
        <el-form-item label="成本价">
          <el-input v-model="temp.price" />
        </el-form-item>
        <el-form-item label="platfrom">
          <el-select v-model="temp.platform" placeholder="platform" filterable size="mini" clearable>
            <el-option
              v-for="item in platforms"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/erp/platformcompetitiveproduct'
import { Translate } from '@/api/baidu'
import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Platformcompetitiveproduct',
  props: ['keyword', 'id', 'image', 'price', 'source', 'isVisible'],
  data() {
    return {
      innerDialogVisible: false,
      title: '添加关键词',
      temp: {
        is_seed: true,
        keyword: '',
        price: 0,
        image: '',
        platform: 'https://shopping.google.com'
      },
      platforms: [
        {
          'label': 'google shopping',
          'value': 'https://shopping.google.com'
        },
        {
          'label': 'Amazon',
          'value': 'https://www.amazon.com'
        }
      ],
      translate_title: '',
      kwInput: '',
      platform: 'https://shopping.google.com',
      listLoading: false,
      order_by: 'position',
      order_desc: 0,
      data: [{ 'products': [] }],
      // pagination
      pagesize: 100,
      page: 1,
      total: 0,
      action: null,
      dialogVisible: false
    }
  },
  watch: {
    isVisible(v) {
      this.dialogVisible = v
      this.translate_title = ''
      if (v) {
        this.kwInput = this.keyword
        this.getList()
      }
    }
  },
  methods: {
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        id: this.id,
        pagesize: this.pagesize,
        source: this.source,
        page: this.page,
        platform: this.platform,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          if (this.data.length === 0 || this.data[0].products === undefined) {
            this.data = [{ 'products': [] }]
          } else {
            this.handleTranslate(this.kwInput)
          }
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleTranslate() {
      Translate({ q: this.kwInput }).then((response) => {
        this.translate_title = response.data.trans_result[0].dst
      })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.title = row
          this.temp.keyword = this.keyword
          this.temp.image = this.image
          this.temp.is_seed = true
          this.temp.price = this.price
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.keyword}?`
          this.temp = row
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改${row.keyword}`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
      }
    },
    handleGetNext(item) {
      this.listLoading = true
      this.translate_title = ''
      Get(null, qs.stringify({
        kw: this.kwInput,
        id: item.id,
        next: true,
        pagesize: this.pagesize,
        page: this.page,
        platform: this.platform,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          if (this.data.length === 0 || this.data[0].products === undefined) {
            this.data = [{ 'products': [] }]
          }
          this.kwInput = this.data[0].keyword
          this.handleTranslate(this.kwInput)
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleSetCrawlCount(item, crawl_count) {
      this.translate_title = ''
      Put(item.id, {
        crawl_count: crawl_count
      }).then((response) => {
        item.crawl_count = crawl_count
        this.$message.success('修改成功')
        this.handleGetNext(item)
      })
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post(this.temp).then(response => {
            this.innerDialogVisible = false
            this.getList()
          })
          break
        case 'delete':
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case 'edit':
          Put(_data.id, {
            keyword: _data.keyword,
            target: _data.target,
            need_check: _data.need_check
          }).then((response) => {
            this.innerDialogVisible = false
            this.$emit('reload')
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    handleDelete() {
      console.log('delete')
    },
    handleAddKeyword() {
      this.temp.keyword = this.keyword
      this.temp.image = this.image
      this.temp.is_seed = true
      this.innerDialogVisible = true
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeMyDialog', false)
    }
  }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .top >>> .el-select .el-input {
    width: 350px;
  }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top {
    padding-left: 20px;
    margin-bottom: 2px;
    margin-top: 5px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 150px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }

  .mt-dialog >>> .el-transfer-panel {
    width: calc(50% - 60px);
  }

  .mt-form >>> .el-select {
    width: 100%;
  }

  .mt-form >>> .el-input__inner {
    width: 100%;
  }

  .mt-dialog >>> .el-dialog {
    margin-top: 60px;
  }

  .mt-dialog >>> .el-dialog__body {
    padding-bottom: 100px;
  }
</style>
